<?php
$config = include_once './config.php';
$type = $_GET['type'];
if ($type == 'add'){
    add($config);
}else if ($type == 'del'){
    del($config);
}else{
    if (file_get_contents("php://input")){
        pub($config);
    }
}
function add($config){
    $post = $_POST;
    if (!$post['project'] || !$post['password'] || !$post['path']) return false;
    $project = $config[$post['project']] ?: [];
    $project['path'][$post['branch']] = $post['path'];
    $project['password'] = $post['password'];
    $config = array_merge($config, [$post['project'] => $project]);
    file_put_contents('config.php', '<?php '.PHP_EOL.'return '. var_export($config, true) . ';');
    header("location:index.php");
}
function del($config){
    $project = $config[$_GET['project']];
    $branch = $_GET['branch'];
    unset($project['path'][$branch]);
    $config = array_merge($config, [$_GET['project'] => $project]);
    file_put_contents('config.php', '<?php '.PHP_EOL.'return '. var_export($config, true) . ';');
    header("location:index.php");
}
function pub($config){
    //1.获取webhook信息
    $requestBody = file_get_contents("php://input");
    if (empty($requestBody)) die('Not WebHook Info!');
    $content = json_decode($requestBody, true);

    //2.获取项目配置信息
    $project = $config[$content['repository']['name']];
    if (!$project) die('Not Find Project Config！');

    //3.判断为需要发布的分支，并且提交数大于0，并且密码正确
    $ref = explode('/', $content['ref']);
    $branch = $ref[array_key_last($ref)];
    if (!isset($project['path'][$branch])) return false; //不存在分支配置
    if ($content['total_commits_count'] <= 0) return false;
    if ($content['password'] != $project['password']) return false;

    //4.进入项目目录拉取代码，PS：这里强制和远程仓库保持一致，即会覆盖本地代码
    $git_command = "git fetch --all && git reset --hard origin/{$branch} && git pull";
    $res = shell_exec("cd {$project['path'][$branch]} && {$git_command} 2>&1");

    //5.记录log日志
    $res_log = '-------------------------'.PHP_EOL;
    $res_log .= $content['user_name'] . ' 在' . date('Y-m-d H:i:s') . '向' . $content['repository']['name'] . '项目的' . $branch . '分支push了' . $content['total_commits_count'] . '个commit：' . PHP_EOL;
    $res_log .= $res.PHP_EOL;
    file_put_contents("git-webhook.log", $res_log, FILE_APPEND);//追加写入
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 最新版本的 Bootstrap 核心 CSS 文件 -->
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<div class="container">
    <h1 style="text-align: center">简易WebHook项目部署管理系统</h1>
    <form action="index.php?type=add" method="post">
        <div class="form-group">
            <label for="project">项目名称</label>
            <input name="project" type="text" class="form-control" id="project" placeholder="请输入项目Git仓库名称">
        </div>
        <div class="form-group">
            <label for="password">WebHook密码</label>
            <input name="password" type="text" class="form-control" id="password" placeholder="请输入webhook密码">
        </div>
        <div class="form-group">
            <label for="branch">部署分支</label>
            <select name="branch" class="form-control" id="branch">
                <option value="master">Master分支</option>
                <option value="develop">Develop分支</option>
                <option value="release">Release分支</option>
                <option value="" disabled>更多分支，请自行编辑脚本添加</option>
            </select>
        </div>
        <div class="form-group">
            <label for="path">部署目录</label>
            <input name="path" type="text" class="form-control" id="path" placeholder="请输入部署目录绝对地址">
        </div>
        <button type="submit" class="btn btn-info">点击提交</button>
    </form>

    <table class="table table-striped">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>#</th>
                    <th>项目名称</th>
                    <th>WebHook密码</th>
                    <th>部署分支</th>
                    <th>部署目录</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php $index = 1; ?>
                <?php foreach ($config as $k => $v){ ?>
                    <?php foreach ($v['path'] as $kk => $vv){ ?>
                <tr>
                    <th scope="row"><?php echo $index++; ?></th>
                    <td><?php echo $k; ?></td>
                    <td><?php echo $v['password']; ?></td>
                    <td><?php echo $kk; ?></td>
                    <td><?php echo $vv; ?></td>
                    <td><a href="index.php?type=del&project=<?php echo $k?>&branch=<?php echo $kk; ?>" class="btn btn-danger">删除</a></td>
                </tr>
                    <?php } ?>
                <?php } ?>
            </tbody>
        </table>
    </table>
</div>
</body>
</html>